﻿using Aspose.Cells;
using IntelligentDataCollection.Models;
using IntelligentDataCollection.Tool;
using System.Data;
using System.Diagnostics;
using System.IO;

namespace IntelligentDataCollection.BUS
{
    public class LogBUS
    {
        public ResponseMessage QueryLog(string starttime, string endtime, string devicename)
        {

            ResponseMessage message = new ResponseMessage();
            List<LogInfo> list = new List<LogInfo>();
            string logPath = AppDomain.CurrentDomain.BaseDirectory + "wwwroot/TestLog/" + devicename;
            if (Directory.Exists(logPath))
            {
                DirectoryInfo folder_base = new DirectoryInfo(logPath);
                FileInfo[] files_base = folder_base.GetFiles("*.csv");  //获取.txt文件
                foreach (var file_txt in files_base)
                {
                    DateTime filetime = file_txt.CreationTime.ToLocalTime().Date;
                    if (string.IsNullOrEmpty(starttime) && string.IsNullOrEmpty(endtime))
                    {
                        LogInfo logInfo = new LogInfo();
                        //获取文件创建时间
                        logInfo.FileName = file_txt.Name;
                        logInfo.FilePath = "/TestLog/" + devicename + "/" + file_txt.Name;
                        logInfo.time = filetime;
                        list.Add(logInfo);
                    }
                    else if (string.IsNullOrEmpty(starttime))
                    {
                        DateTime dt_end = Convert.ToDateTime(endtime).ToLocalTime().Date;
                        if (filetime <= dt_end)
                        {
                            LogInfo logInfo = new LogInfo();
                            //获取文件创建时间
                            logInfo.FileName = file_txt.Name;
                            logInfo.FilePath = "/TestLog/" + devicename + "/" + file_txt.Name;
                            logInfo.time = filetime;
                            list.Add(logInfo);
                        }
                    }
                    else if (string.IsNullOrEmpty(endtime))
                    {
                        DateTime dt_start = Convert.ToDateTime(starttime).ToLocalTime().Date;

                        if (filetime >= dt_start)
                        {
                            LogInfo logInfo = new LogInfo();
                            //获取文件创建时间
                            logInfo.FileName = file_txt.Name;
                            logInfo.FilePath = "/TestLog/" + devicename + "/" + file_txt.Name;
                            logInfo.time = filetime;
                            list.Add(logInfo);
                        }
                    }
                    else
                    {
                        DateTime dt_end = Convert.ToDateTime(endtime).ToLocalTime().Date;
                        DateTime dt_start = Convert.ToDateTime(starttime).ToLocalTime().Date;
                        if (filetime >= dt_start && filetime <= dt_end)
                        {
                            LogInfo logInfo = new LogInfo();
                            //获取文件创建时间
                            logInfo.FileName = file_txt.Name;
                            logInfo.FilePath = "/TestLog/" + devicename + "/" + file_txt.Name;
                            logInfo.time = filetime;
                            list.Add(logInfo);
                        }
                    }
                }
                list = list.OrderByDescending(x => x.time).ThenByDescending(x=>x.FileName).ToList();
            }
            message.total = list.Count();
            message.data = list;
            return message;
        }

        public ResponseMessage DeleteLog(List<LogInfo> logs)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                foreach (var item in logs)
                {
                    string path1 = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "wwwroot";
                    string path2 = item.FilePath;
                    string logPath = path1 + path2;
                    if (File.Exists(logPath))
                    {
                        File.Delete(logPath);
                    }
                }
            }
            catch
            {
                message.errcode = 1;
            }
            return message;
        }

        public ResponseMessage ExportLog(List<LogInfo> logs)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                List<LogInfo> list = new List<LogInfo>();
                foreach (var item in logs)
                {
                    string oldpath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "wwwroot" + item.FilePath;
                    string temp_dir = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "wwwroot/Temp/" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string temppath = temp_dir + "/" + item.FileName;
                    if (!File.Exists(temppath))
                    {
                        if (!Directory.Exists(temp_dir))
                        {
                            Directory.CreateDirectory(temp_dir);
                        }
                        FileStream fs1 = new FileStream(temppath, FileMode.Create, FileAccess.Write);//创建写入文件 
                        fs1.Close();
                    }
                    File.Copy(oldpath, temppath, true);
                    List<StorageData> data_list = new List<StorageData>();

                    using (StreamReader reader = new StreamReader(temppath))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            string[] strings = line.Split(',');

                            string time = strings[0];

                            for (int i = 1; i < strings.Length; i++)
                            {
                                StorageData storageData = new StorageData();
                                storageData.time = time;
                                string kk = strings[i];
                                storageData.data = Convert.ToByte(strings[i], 16);
                                data_list.Add(storageData);
                            }
                        }
                    }

                    string export_dir = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "wwwroot/Export/" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string exportpath = export_dir + "/" + item.FileName;
                    if (!File.Exists(exportpath))
                    {
                        if (!Directory.Exists(export_dir))
                        {
                            Directory.CreateDirectory(export_dir);
                        }
                        FileStream fs2 = new FileStream(exportpath, FileMode.Create, FileAccess.Write);//创建写入文件 
                        fs2.Close();
                    }

                    while (data_list != null && data_list.Count > 0)
                    {
                        int index = data_list.FindIndex(x => x.data == 0x03);
                        if (index > -1)
                        {
                            if (data_list[index + 1].data == 0x03)
                            {
                                int num = (int)data_list[index + 2].data;
                                if (index + num + 4 < data_list.Count)
                                {
                                    byte[] crc_data = new byte[num + 3];
                                    for (int k = 0; k < num + 3; k++)
                                    {
                                        crc_data[k] = (byte)data_list[index + k].data;
                                    }
                                    byte[] crc = Untils.Crc18(crc_data);
                                    if (data_list[index + num + 4].data == crc[0] && data_list[index + num + 3].data == crc[1])
                                    {
                                        string[] all_data = Untils.ToHexs(crc_data).Split(',');
                                        string[] data = new string[all_data.Length - 3];
                                        Array.Copy(all_data, 3, data, 0, data.Length);
                                        string data_str = string.Empty;
                                        for (int n = 0; n < data.Length; n += 2)
                                        {
                                            int data_num = Convert.ToInt32(data[n] + data[n + 1], 16);
                                            data_str += data_list[index].time + "," + data_num.ToString() + ",";
                                        }
                                        File.AppendAllText(exportpath, data_str.Substring(0, data_str.Length - 1) + "\r\n");
                                        data_list.RemoveRange(index, num + 5);
                                    }
                                }
                                else
                                {
                                    data_list.Clear();
                                }
                            }
                            else
                            {
                                if (index == 0)
                                {
                                    data_list.RemoveAt(0);
                                }
                                else
                                {
                                    int num = (int)data_list[index + 1].data;
                                    if (index + num + 4 < data_list.Count)
                                    {
                                        byte[] crc_data = new byte[num + 3];
                                        for (int k = 0; k < num + 3; k++)
                                        {
                                            crc_data[k] = (byte)data_list[index - 1 + k].data;
                                        }
                                        byte[] crc = Untils.Crc18(crc_data);
                                        if (data_list[index + num + 3].data == crc[0] && data_list[index + num + 2].data == crc[1])
                                        {
                                            string[] all_data = Untils.ToHexs(crc_data).Split(',');
                                            string[] data = new string[all_data.Length - 3];
                                            Array.Copy(all_data, 3, data, 0, data.Length);
                                            string data_str = string.Empty;
                                            for (int n = 0; n < data.Length; n += 2)
                                            {
                                                int data_num = Convert.ToInt32(data[n] + data[n + 1], 16);
                                                data_str += data_list[index].time + "," + data_num.ToString() + ",";
                                            }
                                            File.AppendAllText(exportpath, data_str.Substring(0, data_str.Length - 1) + "\r\n");
                                            data_list.RemoveRange(index - 1, num + 5);
                                        }
                                        else
                                        {
                                            data_list.RemoveRange(0, index + 1);
                                        }
                                    }
                                    else
                                    {
                                        data_list.Clear();
                                    }
                                }
                            }
                        }
                        else
                        {
                            data_list.Clear();
                        }
                    }

                    LogInfo logInfo = new LogInfo();
                    logInfo.FileName = item.FileName;
                    logInfo.FilePath = exportpath.Replace(AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "wwwroot", "");
                    list.Add(logInfo);
                }

                message.data = list;
            }
            catch (Exception ex)
            {
                message.errcode = 1;
            }
            return message;
        }

        public static DataTable ImportCompareMeanExcel(string strFilePath)
        {
            Workbook workbook = new Workbook(strFilePath);
            DataTable dtExcel = null;
            try
            {
                Cells cells = workbook.Worksheets[0].Cells;
                dtExcel = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow, cells.MaxColumn, false);//showTitle
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return dtExcel;
        }


    }
}
